﻿using System;
using System.Collections;
using System.Collections.Generic;
using Dentiste.Domain.Providers;

namespace Dentiste.Domain
{
    public class DbSetCustom<T> : IEnumerable<T>
    {
        private readonly IList<T> _list;
        private readonly IProvider<T> _provider;

        public DbSetCustom(IProvider<T> provider)
        {
            _list = new List<T>();
            _provider = provider;
        }

        public IEnumerator<T> GetEnumerator()
        {
            return _list.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return _list.GetEnumerator();
        }

        public void Add(T entity)
        {
            if (_list.Contains(entity)) return;
            _list.Add(entity);
        }

        public void Remove(T entity)
        {
            if (!_list.Contains(entity)) return;
            _list.Remove(entity);
        }

        public void RemoveAndDelete(T entity)
        {
            if (!_list.Contains(entity)) return;
            _provider.Delete(entity);
            _list.Remove(entity);
        }

        public T AddAndPersist(T entity)
        {
            if (_list.Contains(entity)) throw new Exception("The entity already exists");
            T i = _provider.Insert(entity);
            _list.Add(entity);
            return i;
        }
    }
}